const { MongoClient } = require('mongodb');
const { ERR_DATABASE, MONGO_URL } = require('../config');

let db;

const connectDB = async () => {
  try {
    const client = new MongoClient(MONGO_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    await client.connect();
    console.log('MongoDB 连接成功...');
    db = client.db(ERR_DATABASE); // 保存数据库连接
  } catch (err) {
    console.error('MongoDB 连接失败: ', err);
    process.exit(1);
  }
};

const getDB = () => {
  if (!db) {
    throw new Error('Database 未连接');
  }
  return db;
};

module.exports = { connectDB, getDB };
